package com.party.web.web.controller.system;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.common.redis.StringJedis;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.city.Area;
import com.party.core.model.commune.CMemberInfo;
import com.party.core.model.commune.CMemberRecommend;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.member.Industry;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.PartnerMember;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.city.IAreaService;
import com.party.core.service.commune.ICMemberInfoService;
import com.party.core.service.commune.ICMemberRecommendService;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.member.IIndustryService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.system.ISysRoleService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.security.CurrentUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会员控制器 Created by wei.li
 *
 * @date 2017/3/14 0014
 * @time 17:52
 */

@Controller
@RequestMapping(value = "/system/member")
public class MemberController {

    protected static Logger logger = LoggerFactory.getLogger(MemberController.class);
    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IIndustryService industryService;
    @Autowired
    private IAreaService areaService;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private ICMemberRecommendService memberRecommendService;
    @Autowired
    private ICMemberInfoService memberInfoService;

    @Value("#{party['mic.url']}")
    private String micUrl;

    /**
     * 查看会员信息
     *
     * @param id 会员编号
     * @return 会员信息
     */
    @RequestMapping(value = "memberView")
    public ModelAndView memberView(String id) {
        ModelAndView modelAndView = new ModelAndView("system/member/memberInfo");

        try {
            String industryId = null;
            String cityId = null;
            Member member = memberService.get(id);
            if (null == member) {
                MemberGroup memberGroup = memberGroupService.get(id);
                if (null == memberGroup) {
                    return modelAndView;
                } else {
                    industryId = memberGroup.getIndustry();
                    cityId = memberGroup.getCity();
                    modelAndView.addObject("member", memberGroup);
                    modelAndView.addObject("isGroup", true);
                }
            } else {
                industryId = member.getIndustry();
                cityId = member.getCity();
                modelAndView.addObject("member", member);
            }
            if (!Strings.isNullOrEmpty(industryId)) {
                Industry industry = industryService.get(industryId);
                modelAndView.addObject("industry", industry);
            }
            if (!Strings.isNullOrEmpty(cityId)) {
                Area area = areaService.get(cityId);
                modelAndView.addObject("city", area);
            }

        } catch (Exception e) {
            logger.error("查询会员信息异常", e);
        }
        return modelAndView;
    }


    /**
     * 前端行业分类联动
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getIndustryByParentId")
    public List<Industry> getIndustryByParentId(String industryId) {
        Industry industry = new Industry();
        industry.setParentId(industryId);
        List<Industry> industries = industryService.list(industry);
        return industries;
    }

    /**
     * 前端城市联动
     *
     * @param cityId
     * @return
     */
    @ResponseBody
    @RequestMapping("getCityByParentId")
    public List<Area> getCityByParentId(String cityId) {
        Area area = new Area();
        area.setParentId(cityId);
        List<Area> areas = areaService.list(area);
        return areas;
    }

    /**
     * 验证用户名或者手机号
     *
     * @param userId
     * @param type
     * @return
     */
    @ResponseBody
    @RequestMapping("checkUniqueProperty")
    public AjaxResult checkUniqueProperty(String key, String value, String userId, Integer type, String roleName) {
        if (StringUtils.isEmpty(key)) {
            return AjaxResult.error("请选择验证用户名或是手机号");
        }
        if (StringUtils.isEmpty(value)) {
            return AjaxResult.error("请输入需要验证的值");
        }
        if ("mobile".equals(key) && null == type) {
            return AjaxResult.error("用户类型不能为空");
        }
        try {
            List<Member> members = memberService.checkUserName(key, value, userId, type);
            if (members.size() > 0) {
                if (StringUtils.isNotEmpty(userId)) {
                    return AjaxResult.success(false);
                }
                if (StringUtils.isNotEmpty(roleName) && members.size() == 1) {
                    boolean hasPartner = sysRoleService.hasRole(members.get(0).getId(), roleName);
                    if (hasPartner) {
                        return AjaxResult.success(false);
                    } else {
                        return AjaxResult.success(true);
                    }
                }
                return AjaxResult.success(false);
            }
            return AjaxResult.success(true);
        } catch (Exception e) {
            logger.error("验证用户名或手机号异常", e);
            return AjaxResult.error("验证用户名或手机号异常");
        }
    }


    /**
     * 根据用户手机或用户名查询
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("findMemberByPhoneOrName")
    public AjaxResult findMemberByPhoneOrName(String property, String value) {
        try {
            List<Map<String, Object>> list = memberService.findMemberByPhoneOrName(property, value, Member.MEMBER_PERSONAL);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("根据用户手机或用户名查询失败", e);
            return new AjaxResult(false);
        }
    }


    /**
     * 根据用户手机或用户名查询 当前机构下的用户
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("findPartnerMemberByPhoneOrName")
    public AjaxResult findPartnerMemberByPhoneOrName(String property, String value, String pmId, String actId) {
        try {
            CurrentUser currentUser = RealmUtils.getNewCurrentUser();
            String partnerId = currentUser.getId();
            List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
            if (StringUtils.isNotEmpty(pmId)) {
                PartnerMember partnerMember = partnerMemberService.get(pmId);
                partnerId = partnerMember.getPartnerId();
                orgIds = memberGroupService.getChildWithMy(partnerId);
            }
            if (StringUtils.isNotEmpty(actId)) {
                Activity activity = activityService.get(actId);
                orgIds = memberGroupService.getChildWithMy(activity.getMember());
            }
            List<Map<String, Object>> list = memberService.findPartnerMemberByPhoneOrName2(property, value, Member.MEMBER_PERSONAL, orgIds);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("根据用户手机或用户名查询失败", e);
            return new AjaxResult(false);
        }
    }

    @ResponseBody
    @RequestMapping("getMember")
    public AjaxResult getMember(String id) {
        Map<String, Object> map = new HashMap<String, Object>();
        Member member = memberService.get(id);
        String inParent = "";
        if (StringUtils.isNotEmpty(member.getIndustry())) {
            Industry industry = industryService.get(member.getIndustry());
            inParent = industry.getParentId();
        }

        String arParent = "";
        if (StringUtils.isNotEmpty(member.getCity())) {
            Area area = areaService.get(member.getCity());
            arParent = area.getParentId();
        }

        map.put("inParent", inParent);
        map.put("arParent", arParent);
        map.put("member", member);
        return AjaxResult.success(map);
    }

    /**
     * 个人中心
     *
     * @return
     */
    @RequestMapping("memberIndex")
    public String memberIndex() {
        return "redirect:/merchant/analyze/detail.do";
    }

    /**
     * 资金管理
     *
     * @return
     */
    @RequestMapping("fundMana")
    public String fundMana() {
        return "redirect:/moneyManagement/allMoneyList.do";
    }

    @RequestMapping(value = "memberViewWithShare")
    public ModelAndView memberViewWithShare(String id, String projectId) {
        ModelAndView mv = new ModelAndView("system/member/memberInfoWithShare");
        try {
            if (StringUtils.isNotEmpty(id)) {
                Member member = memberService.get(id);
                if (StringUtils.isNotEmpty(member.getIndustry())) {
                    Industry industry = industryService.get(member.getIndustry());
                    mv.addObject("industry", industry);
                }

                if (StringUtils.isNotEmpty(member.getCity())) {
                    Area area = areaService.get(member.getCity());
                    mv.addObject("city", area);
                }
                mv.addObject("member", member);

                String url = micUrl + "project/project_detail.html?id=" + projectId;
                CrowdfundEvent crowdfundEvent = crowdfundEventService.findByProjectId(projectId);
                if (null != crowdfundEvent && YesNoStatus.YES.getCode().equals(crowdfundEvent.getIsMultiple())) {
                    url = micUrl + "project/project_multi_detail.html?id=" + projectId;
                }
                mv.addObject("zcLink", url);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }

    /**
     * 查看推荐人的会员信息
     *
     * @param pmId 机构关系id
     * @return 会员信息
     */
    @RequestMapping(value = "recommendMemberView")
    public ModelAndView recommendMemberView(String pmId) {

        if (StringUtils.isEmpty(pmId)) {
            return null;
        }
        ModelAndView modelAndView = new ModelAndView("system/member/recommendMemberInfo");
        try {


            //自填推荐人
            String recommendUsername = "";
            PartnerMember partnerMember1 = partnerMemberService.get(pmId);
            if (partnerMember1 != null) {
                CMemberInfo byMemberId = memberInfoService.getByMemberId(partnerMember1.getMemberId());
                if (byMemberId != null) {
                    recommendUsername = byMemberId.getRecommendUsername();
                    modelAndView.addObject("recommendUsername", recommendUsername);
                }
            }


            String industryId = null;
            String cityId = null;
            String id = "";

            //通过传入的pmId 获取推荐人的用户id
            PartnerMember partnerMember = new PartnerMember();
            CMemberRecommend cMemberRecommend = new CMemberRecommend();
            cMemberRecommend.setuId(pmId);
            List<CMemberRecommend> list = memberRecommendService.list(cMemberRecommend);
            if (list.size() > 0) {
                partnerMember = partnerMemberService.get(list.get(0).getParentId());
                if (partnerMember == null) {
                    return modelAndView;
                } else {
                    Member member = memberService.get(partnerMember.getMemberId());
                    if (member == null) {
                        return modelAndView;
                    } else {
                        id = member.getId();
                    }
                }
            }

            Member member = memberService.get(id);
            if (null == member) {
                MemberGroup memberGroup = memberGroupService.get(id);
                if (null == memberGroup) {
                    return modelAndView;
                } else {
                    industryId = memberGroup.getIndustry();
                    cityId = memberGroup.getCity();
                    modelAndView.addObject("member", memberGroup);
                    modelAndView.addObject("isGroup", true);
                }
            } else {
                industryId = member.getIndustry();
                cityId = member.getCity();
                modelAndView.addObject("member", member);
            }
            if (!Strings.isNullOrEmpty(industryId)) {
                Industry industry = industryService.get(industryId);
                modelAndView.addObject("industry", industry);
            }
            if (!Strings.isNullOrEmpty(cityId)) {
                Area area = areaService.get(cityId);
                modelAndView.addObject("city", area);
            }

        } catch (Exception e) {
            logger.error("查询会员信息异常", e);
        }
        return modelAndView;
    }

    /**
     * 前端分社下级分类联动
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("getMemberGroupUserBymemberGroupId")
    public AjaxResult getMemberGroupUserBymemberGroupId(String memberGroupId) {
        if (StringUtils.isEmpty(memberGroupId)) {
            return AjaxResult.error("参数为空");
        }
        MemberGroup memberGroup = memberGroupService.get(memberGroupId);
        if (memberGroup == null) {
            return AjaxResult.error("机构不存在");
        }
        List<MemberGroup> memberGroupUsers = Lists.newArrayList();
        List<MemberGroup> childList = memberGroupService.getChildList(memberGroup.getId());
        memberGroupUsers.add(memberGroup);
        for (MemberGroup mgObj : childList) {
            memberGroupUsers.add(mgObj);
        }
        return AjaxResult.success(memberGroupUsers);
    }
}
